<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
<!--    卡片试图-->
    <el-card class="box-card">
<!--      搜索-->
      <el-row :gutter="30">
        <el-col :span="10">
          <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getUserlist">
            <el-button slot="append" icon="el-icon-search" @click="getUserlist"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogvisble = true">添加用户</el-button>
        </el-col>
      </el-row>
      <!--    表格-->
      <el-table
        :data="userlist"
        stripe
        style="width: 100%"
        border>
        <el-table-column type="index" label="*"></el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column label="状态(O/F)">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="userstatuchange"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <el-tooltip effect="dark" content="编辑" placement="top" :enterable="false">
              <el-button @click="editdialog(scope.row.id)" size="mini" type="primary" icon="el-icon-edit"></el-button>
            </el-tooltip>
            <el-tooltip effect="dark" content="删除" placement="top" :enterable="false">
              <el-button @click="removeuserbyid(scope.row.id)" size="mini" type="danger" icon="el-icon-delete"></el-button>
            </el-tooltip>
            <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false">
              <el-button @click="setRole(scope.row)" size="mini" type="warning" icon="el-icon-setting"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
<!--      分页-->
      <el-pagination background layout="prev, pager, next" :total="100"></el-pagination>
    </el-card>
<!--    添加用户的对话框-->
    <el-dialog @close="adddialogclose" title="添加用户" :visible.sync="addDialogvisble" width="50%">
      <el-form :model="addForm" :rules="addFormRules" ref="addFormref" label-width="70px" class="demo-ruleForm">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
    <el-button @click="addDialogvisble = false">取 消</el-button>
    <el-button type="primary" @click="adduser">确 定</el-button>
  </span>
    </el-dialog>
<!--    修改用户-->
    <el-dialog @close="editclose"
      title="修改用户"
      :visible.sync="editdialogvis"
      width="50%">
      <el-form :model="editForm" :rules="editFormrules" ref="editFormref" label-width="70px">
        <el-form-item label="用户名">
          <el-input disabled v-model="editForm.username"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item prop="mobile" label="手机号">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
    <el-button @click="editdialogvis = false">取 消</el-button>
    <el-button type="primary" @click="edituserinfo">确 定</el-button>
  </span>
    </el-dialog>
<!--    分配角色-->
    <el-dialog @close="setroledialogclose"
      title="分配角色"
      :visible.sync="setroledialogVisible"
      width="50%">
      <div>
        <p>当前用户：{{userinfo.username}}</p>
        <p>当前角色：{{userinfo.role_name}}</p>
        <p>分配新角色：
          <el-select v-model="selectroleid" placeholder="请选择">
            <el-option
              v-for="item in roleslist"
              :key="item.id"
              :label="item.roleName"
              :value="item.id">
            </el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
    <el-button @click="setroledialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="saveroleinfo">确 定</el-button>
  </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Users',
  data () {
    var checkEmail = (rules, values, cb) => {
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      if (regEmail.test(values)) {
        return cb()
      }
      cb(new Error('请输入合法格式邮箱'))
    }
    var checkmobile = (rules, values, cb) => {
      const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      if (regMobile.test(values)) {
        return cb()
      }
      cb(new Error('请输入正确的手机号码'))
    }
    return {
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 10
      },
      userlist: [],
      tatal: 0,
      addDialogvisble: false,
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      addFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' }, { min: 3, max: 10, message: '用户名长度在3-10', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }, { min: 6, max: 15, message: '密码长度在3-10', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' }, { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号码', trigger: 'blur' }, { valuedator: checkmobile, trigger: 'blur' }
        ]
      },
      editdialogvis: false,
      editForm: {},
      editFormrules: {
        email: [
          { required: true, message: '请输入用户邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机', trigger: 'blur' },
          { validator: checkmobile, trigger: 'blur' }
        ]
      },
      setroledialogVisible: false,
      userinfo: {},
      roleslist: [],
      selectroleid: ''
    }
  },
  created() {
    this.getUserlist()
  },
  methods: {
    async getUserlist () {
      const { data: res } = await this.$http.get('users', { params: this.queryInfo })
      if (res.meta.status !== 200) return this.$message.error('获取用户列表失败')
      this.userlist = res.data.users
      this.toal = res.data.toal
    },
    // 监听switch
    async userstatuchange (userinfo) {
      /* const { data: res } = await this.$http.put(`users/${userinfo.id}/state/${userinfo.mg_state}`)
      if (res.meta.status !== 200) {
        userinfo.mg_state = !userinfo.mg_state
        return this.$message.error('更新用户状态失败')
      }
      this.$message.success('更新用户状态成功!') */
    },
    adddialogclose () {
      this.$refs.addFormref.resetFields()
    },
    adduser () {
      this.$refs.addFormref.validate(async valid => {
        if (!valid) return
        // 发起添加用户网络请求
        const { data: res } = await this.$http.post('users', this.addForm)
        if (res.meta.status !== 201) {
          this.$message.error('添加用户失败')
        }
        this.$message.success('添加用户成功')
        this.addDialogvisble = false
        this.getUserlist()
      })
    },
    async editdialog (id) {
      const { data: res } = await this.$http.get('users/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('查询失败')
      }
      this.editForm = res.data
      this.editdialogvis = true
    },
    editclose () {
      this.$refs.editFormref.resetFields()
    },
    edituserinfo () {
      this.$refs.editFormref.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put('users/' + this.editForm.id, { email: this.editForm.email, mobile: this.editForm.mobile })
        if (res.meta.status !== 200) {
          return this.$message.error('用户信息更新失败')
          // 关闭对话框
        }
        this.editdialogvis = false
        this.getUserlist()
        this.$message.success('更新用户列表成功')
      })
    },
    async removeuserbyid (id) {
      // 询问用户是否删除数据
      const comfirmres = await this.$confirm('此操作将永久该用户, 是否继续?', '警告！', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (comfirmres !== 'confirm') {
        return this.$message.info('已经取消删除')
      }
      const { data: res } = await this.$http.delete('users/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('删除失败!')
      }
      this.$message.success('删除成功')
      this.getUserlist()
    },
    async setRole (userinfo) {
      this.userinfo = userinfo
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取失败')
      }
      this.roleslist = res.data
      this.setroledialogVisible = true
    },
    async saveroleinfo () {
      if (!this.selectroleid) {
        return this.$message.error('请选择要分配的角色')
      }
      const { data: res } = await this.$http.put(`users/${this.userinfo.id}/role`,
        { rid: this.selectroleid })
      if (res.meta.status !== 200) {
        return this.$message.error('更新失败')
      }
      this.$message.success('更新成功')
      this.getUserlist()
      this.setroledialogVisible = false
    },
    setroledialogclose () {
      this.selectroleid = ''
      this.userinfo = ''
    }
  }
}
</script>

<style scoped>
  .box-card, .el-table{
    border-radius: 10px;
  }
  .el-table{
    margin-top: 15px;
  }
  .el-pagination{
    text-align: center;
    margin-top: 20px;
  }
</style>
